package Array;

import org.junit.Test;

import java.util.*;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Array
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-11-26  17:53
 * @Description: TODO
 * @Version: 1.0
 */
public class 水果成篮904 {

    public int totalFruit(int[] fruits) {
        int result = Integer.MIN_VALUE;
        int left = 0;
        int right = 0;
        while (right < fruits.length) {
            while (checkFruit(left, right, fruits)) {
                result = Math.max(result, right - left);
                left++;
            }
            right++;
        }
        result = Math.max(result, right - left);
        return result;
    }

    private boolean checkFruit(int left, int right, int[] fruits) {
        // 检查lef right 之间是否包含三类元素
        HashSet<Integer> set = new HashSet<>();
        for (int i = left; i <= right; i++) {
            set.add(fruits[i]);
        }
        return set.size() > 2;
    }

    public int totalFruit2(int[] fruits) {
        int n = fruits.length;
        Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();

        int left = 0, ans = 0;
        for (int right = 0; right < n; ++right) {
            cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
            while (cnt.size() > 2) {
                // 开始删除了
                // 将Hashmap中元素fruits[left] -1
                cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
                // 判断是fruits[left] 是否等于0 如果是那就删除或者元素
                if (cnt.get(fruits[left]) == 0) {
                    cnt.remove(fruits[left]);
                }
                // 一直减少
                ++left;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }

    @Test
    public void test() {
        int i = totalFruit(new int[]{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4});
        System.out.println(i);
    }
}
